import * as zrender from 'zrender';
import { barHeight, barMargin } from '../../config';
import { getUniquePersons } from '../../utils';

/**
 * 绘制水平线配置选项
 */
export interface HorizontalLinesOptions {
  /** 线条起始 x 坐标 */
  startX: number;
  /** 线条结束 x 坐标 */
  endX: number;
  /** 线条颜色 */
  strokeColor?: string;
  /** 线条宽度 */
  lineWidth?: number;
  /** z-index 层级 */
  zIndex?: number;
}

/**
 * 绘制水平分隔线（统一组件）
 * @param {object} zr ZRender实例
 * @param {object} chartState 图表状态对象
 * @param {PersonSchedule[]} schedules 人员排班数据
 * @param {HorizontalLinesOptions} options 绘制选项
 */
export function drawHorizontalLines(
  zr: any,
  chartState: ChartState,
  schedules: PersonSchedule[],
  options: HorizontalLinesOptions,
) {
  if (!schedules || schedules.length === 0) {
    return;
  }

  const {
    startX,
    endX,
    strokeColor = '#e0e0e0',
    lineWidth = 1,
    zIndex = 1,
  } = options;

  // 获取去重后的人员列表
  const uniquePersons = getUniquePersons(schedules);

  // 计算视口中可见的行范围
  const firstVisibleRow = Math.max(0, Math.floor(chartState.lastScrollY / (barHeight + barMargin)));
  const lastVisibleRow = Math.min(uniquePersons.length - 1, firstVisibleRow + Math.ceil(chartState.canvasHeight / (barHeight + barMargin)) + 1);

  // 绘制每行的顶部分隔线
  for (let index = firstVisibleRow; index <= lastVisibleRow; index++) {
    const y = chartState.chartStartY + index * (barHeight + barMargin) - chartState.lastScrollY;

    // 跳过超出视口的线条
    if (y < 0 || y > chartState.canvasHeight) {
      continue;
    }

    const separator = new zrender.Line({
      shape: {
        x1: startX,
        y1: y,
        x2: endX,
        y2: y,
      },
      style: {
        stroke: strokeColor,
        lineWidth,
      },
      z: zIndex,
      silent: true,
    });
    zr.add(separator);
  }

  // 绘制最后一行的底部分隔线
  if (lastVisibleRow >= 0 && lastVisibleRow < uniquePersons.length) {
    const lastRowY = chartState.chartStartY + lastVisibleRow * (barHeight + barMargin) - chartState.lastScrollY;
    const bottomLineY = lastRowY + barHeight;

    // 检查底部线是否在可视范围内
    if (bottomLineY >= 0 && bottomLineY <= chartState.canvasHeight) {
      const bottomSeparator = new zrender.Line({
        shape: {
          x1: startX,
          y1: bottomLineY,
          x2: endX,
          y2: bottomLineY,
        },
        style: {
          stroke: strokeColor,
          lineWidth,
        },
        z: zIndex,
        silent: true,
      });
      zr.add(bottomSeparator);
    }
  }
}
